package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.dao.GoodsDao;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuAttrValue;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

//索引和数据的增删改查
@Service
public class ListServiceImpl implements ListService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ProductFeignClient productFeignClient;

    @Override//增加索引 上架
    public void onSale(Long skuId) {
        Goods goods = new Goods();
        //Goods的数据来源
        //1、库存表 sku_info
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuInfo.getId());
        goods.setTitle(skuInfo.getSkuName());
        System.out.println("设置的title是： " + skuInfo.getSkuName());
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        //--价格需要查询实时价格
        BigDecimal price = productFeignClient.getPrice(skuInfo.getId());
        goods.setPrice(price.doubleValue());
        //创建时间
        Calendar instance = Calendar.getInstance();//当前时间-最新版
        instance.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        goods.setCreateTime(instance.getTime());
//======goods.setCreateTime(new Date());==============================

        //2、品牌表 base_trademark
        BaseTrademark baseTrademark = productFeignClient.getBaseTrademark(skuInfo.getTmId());
        goods.setTmId(baseTrademark.getId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());

        //3、三级分类视图 base_category_view
        BaseCategoryView baseCategoryView =
                productFeignClient.getBaseCategory(skuInfo.getCategory3Id());
        goods.setCategory1Id(baseCategoryView.getCategory1Id());
        goods.setCategory1Name(baseCategoryView.getCategory1Name());
        goods.setCategory2Id(baseCategoryView.getCategory2Id());
        goods.setCategory2Name(baseCategoryView.getCategory2Name());
        goods.setCategory3Id(baseCategoryView.getCategory3Id());
        goods.setCategory3Name(baseCategoryView.getCategory3Name());

        //4、sku对应的平台属性表
        List<SkuAttrValue> skuAttrValueList =
                productFeignClient.getSkuAttrValue(skuInfo.getId());
        //==========     偷天换日   =泛型转换============
        //for (SkuAttrValue attrValue : skuAttrValue) {}
        List<SearchAttr> attrList = skuAttrValueList.stream().map(skuAttrValue -> {
            SearchAttr searchAttr = new SearchAttr();
            searchAttr.setAttrId(skuAttrValue.getBaseAttrInfo().getId());
            searchAttr.setAttrName(skuAttrValue.getBaseAttrInfo().getAttrName());
            searchAttr.setAttrValue(skuAttrValue.getBaseAttrValue().getValueName());
            return searchAttr;
        }).collect(Collectors.toList());
        //=========================================
        goods.setAttrs(attrList);
        goodsDao.save(goods);
    }

    @Override//删除索引 取消上架
    public void cancelSale(Long skuId) {
        //删除
        goodsDao.deleteById(skuId);
    }

    @Override
    public void hotScore(Long skuId) {

        //原子性问题  使用redis自带的自增方法
        /*Double hotScore = redisTemplate.opsForZSet().score("hotScore", skuId);
        hotScore ++;
        redisTemplate.opsForZSet().add("hotScore", skuId,hotScore);*/
        Double hotScore = redisTemplate.opsForZSet().incrementScore("hotScore", skuId, 1);
        if (hotScore % 10 == 0) {
            //1、查询
            Optional<Goods> byId = goodsDao.findById(skuId);
            Goods goods = byId.get();
            goods.setHotScore(Math.round(hotScore));
            //2、保存
            goodsDao.save(goods);
        }
    }

    //开始搜索  最难的地方
    @Override
    public SearchResponseVo list(SearchParam searchParam) {

        //1、构建条件请求对象 （上百行，抽取出去
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            //2、执行搜索
            SearchResponse searchResponse = restHighLevelClient.
                    search(searchRequest, RequestOptions.DEFAULT);
            //3、解析结果  (抽取出来
            SearchResponseVo vo = parseSearchResponse(searchResponse);
            //当前页
            vo.setPageNo(searchParam.getPageNo());
            //每页数
            vo.setPageSize(searchParam.getPageSize());
            //总页数   =(总条数 + 总页数-1)/每页数
            long totalPages = (vo.getTotal() + vo.getPageSize() - 1) / vo.getPageSize();
            vo.setTotalPages(totalPages);
            return vo;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //解析搜索结果
    private SearchResponseVo parseSearchResponse(SearchResponse searchResponse) {
        SearchResponseVo vo = new SearchResponseVo();
        SearchHits hits = searchResponse.getHits();
        //1、总条数
        long totalHits = hits.getTotalHits();
        System.out.println("总条数：" + totalHits);
        vo.setTotal(totalHits);
        //2、商品结果集
        SearchHit[] hits1 = hits.getHits();
        //需要的是list<Goods>, ==偷天换日==
        List<Goods> goodsList = Arrays.stream(hits1).map(searchHit -> {
            String sourceAsString = searchHit.getSourceAsString();
            Goods goods = JSONObject.parseObject(sourceAsString, Goods.class);
            System.out.println("无高亮的名称："+goods.getTitle());
            //解析出高亮的名称 将无高亮的名称替换掉
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            if (null != highlightFields && highlightFields.size() > 0){
                HighlightField title = highlightFields.get("title");
                goods.setTitle(title.fragments()[0].toString());
            }
            return goods;
        }).collect(Collectors.toList());
        vo.setGoodsList(goodsList);
        //3、品牌集合===========================================
        Map<String, Aggregation> aggregationMap = searchResponse.getAggregations().asMap();
        ParsedLongTerms tmIdAgg = (ParsedLongTerms) aggregationMap.get("tmIdAgg");
            //偷天换日
        List<SearchResponseTmVo> trademarkList =
                tmIdAgg.getBuckets().stream().map(bucket -> {
                    SearchResponseTmVo tmVo = new SearchResponseTmVo();
                    tmVo.setTmId(Long.parseLong(bucket.getKeyAsString()));
                    //品牌名称  获取子辈bucket
                    Aggregations aggregations = bucket.getAggregations();
                    ParsedStringTerms tmNameAgg = aggregations.get("tmNameAgg");
                    tmVo.setTmName(tmIdAgg.getBuckets().get(0).getKeyAsString());
                    ParsedStringTerms tmLogoUrlAgg = aggregations.get("tmLogoUrlAgg");
                    tmVo.setTmLogoUrl(tmLogoUrlAgg.getBuckets().get(0).getKeyAsString());
                    return tmVo;
                }).collect(Collectors.toList());
        vo.setTrademarkList(trademarkList);

        //4、平台集合===========================================
        ParsedNested attrsAgg = (ParsedNested) aggregationMap.get("attrsAgg");
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attrIdAgg");
        List<SearchResponseAttrVo> attrsList = attrIdAgg.getBuckets().stream().map(bucket -> {
            SearchResponseAttrVo attrVo = new SearchResponseAttrVo();
            //平台属性ID
            attrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            //平台属性名称
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            //平台属性值列表
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            attrVo.setAttrValueList(attrValueAgg.getBuckets().stream().
                    map(Terms.Bucket::getKeyAsString).collect(Collectors.toList()));
            return attrVo;
        }).collect(Collectors.toList());
        vo.setAttrsList(attrsList);
        return vo;
    }

    //构建条件对象（抽取出来
    public SearchRequest buildSearchRequest(SearchParam searchParam) {

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //创建组合对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1、关键词
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", keyword));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //2、过滤条件
        //2.1品牌
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)) {
            String[] t = StringUtils.split(trademark, ":");
            //0：品牌ID  1：品牌名称
            boolQueryBuilder.filter(QueryBuilders.termQuery("tmId", t[0]));
        }
        //2.2三级分类
        Long category1Id = searchParam.getCategory1Id();
        if (null != category1Id) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id", category1Id));
        }
        Long category2Id = searchParam.getCategory2Id();
        if (null != category2Id) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id", category2Id));
        }
        Long category3Id = searchParam.getCategory3Id();
        if (null != category3Id) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id", category3Id));
        }
        //2.3平台属性   ===超难===
        String[] props = searchParam.getProps();
        if (null != props && props.length > 0) {
            //第二层bool 传进第一层bool中
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            for (String prop : props) {
                String[] p = prop.split(":");
                //第三个bool
                BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", p[0]));
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", p[1]));
                //塞入第二层bool中 嵌套
                boolQuery.must(QueryBuilders.nestedQuery("attrs", subBoolQuery, ScoreMode.None));
            }
            //第一层bool
            boolQueryBuilder.filter(boolQuery);
        }

        //设置组合条件对象
        searchSourceBuilder.query(boolQueryBuilder);

        //2.4排序
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)) {
            String[] o = order.split(":");
            String name = null;
            switch (o[0]) {
                case "1": name = "hotScore";break;
                case "2": name = "price";break;
            }
            searchSourceBuilder.sort(name, o[1].equals("asc") ? SortOrder.ASC : SortOrder.DESC);
        } else {
            searchSourceBuilder.sort("hotScore", SortOrder.DESC);
        }

        //2.5分页
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        searchSourceBuilder.from((pageNo - 1) * pageSize);
        searchSourceBuilder.size(pageSize);

        //2.6品牌聚合   ==桶聚合
        //复杂聚合  父-2个儿子
        searchSourceBuilder.aggregation(
                AggregationBuilders.terms("tmIdAgg").field("tmId")
                .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName"))
                .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl")));

        //2.7平台属性聚合
        searchSourceBuilder.aggregation(
                AggregationBuilders.nested("attrsAgg","attrs")//爷爷辈
                .subAggregation(AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")//子辈
                .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))//俩孙子辈
                .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"))));

        //2.8高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .field("title")
                .preTags("<font color='red'>")
                .postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
        HighlightBuilder highlighter = searchSourceBuilder.highlighter();
        highlighter.preTags("<span style='color:orange'>")
                   .postTags("</span>");

        //打印DSL语句--检查
        System.out.println(searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        searchRequest.indices("goods");
        return searchRequest;
    }


}
